package cn.mesmile.emqtt;

import cn.hutool.core.date.DateUtil;
import cn.mesmile.emqtt.client.EmqClient;
import cn.mesmile.emqtt.enums.MqttQosEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.annotation.PostConstruct;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author zb
 * @date 2021/6/22 10:46
 * @Description Emqx broker  开源免费  后台管理端口18083
 *
 *    IOT 相关
 *    https://iot.mushuwei.cn/#/iot-platform
 *
 *   消息中心相关
 *      https://www.sohu.com/a/240797984_575744
 *      https://blog.csdn.net/sunhuiliang85/article/details/78235866
 *      https://baijiahao.baidu.com/s?id=1627764016075566196&wfr=spider&for=pc
 *
 *   规则引擎相关
 *   https://www.bilibili.com/video/BV1Pa4y1a7u6?from=search&seid=15391697081844647167
 *   https://github.com/HappySnailSunshine/JavaInterview/blob/master/docs/Drools.md
 */
@SpringBootApplication
public class EmqttApplication {

    public static void main(String[] args) {
        SpringApplication.run(EmqttApplication.class, args);
    }

    @Autowired
    private EmqClient emqClient;

    @PostConstruct
    public void init(){
        AtomicInteger count = new AtomicInteger(1);
        // 连接
        emqClient.connect();
        System.out.println(">>>>>>>>>>>> 开始发布消息");
        // 发布消息
        new Thread(() ->{
            while (true) {
                emqClient.publish("testtopic/123", "hello world. "+ DateUtil.now(), MqttQosEnum.Qos2 , false);
                if (count.get() > 3){
                    return;
                }
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count.getAndIncrement();
            }
        }).start();
        System.out.println(">>>>>>>>>>>> 开始订阅");
        // 订阅
        emqClient.subscribe("testtopic/#", MqttQosEnum.Qos2);
    }

}
